package dlb.busstop.utils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;

import android.content.Context;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import dlb.busstop.data.BusStop;
import dlb.busstop.json.BusStopListGrabber;
import dlb.busstop.json.JSONParser;

public class SuggestionAdapter extends ArrayAdapter<String>{

	private List<BusStop> mItems = new ArrayList<BusStop>();
	
	public SuggestionAdapter(Context context, int resource) {
		super(context, resource);
	}
	
	@Override
    public Filter getFilter() {
        Filter filter = new Filter() {
            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                FilterResults filterResults = new FilterResults();
                if (constraint != null && constraint.length() >= 3) {
                    try {
						mItems = BusStopListGrabber.getInstance(JSONParser.getInstance()).grabBusStopList(null, 0, constraint.toString());
					} catch (JSONException e) {
						throw new RuntimeException(e);
					} catch (IOException e) {
						throw new RuntimeException(e);
					}
                    
                    filterResults.values = mItems;
                    filterResults.count = mItems.size();
                }
                return filterResults;
            }

            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {
                if (results != null && results.count > 0) {
                    notifyDataSetChanged();
                }
                else {
                    notifyDataSetInvalidated();
                }
            }};
        return filter;
    }
		
	@Override
	public int getCount() {
		return mItems.size();
	}
	
	@Override
	public String getItem(int position) {
		return mItems.get(position).getDescription();
	}
}
